import { useState, useEffect, useCallback } from 'react'
import { Table } from 'antd'
import { initPageType, usePageChange } from '@hs-admin/utils'
import { postCompanyInfoDetailBranchUnit } from '@/api/companyDetail/CompanyDevelopment.ts'
import './Branches.css'

const initPage: initPageType = {
  current: 1,
  pageSize: 10,
  total: 0,
  morePageOptions: {
    showSizeChanger: true,
    showQuickJumper: true,
    showTotal: (total: number) => `共 ${total} 条数据`,
    pageSizeOptions: [10, 20, 30, 40]
  }
}

const Branches = ({ companyCode }: { companyCode: string }) => {
  const [data, setData] = useState([])

  const getList = useCallback(
    async (page: number, pageSize: number) => {
      const params = {
        companyCode,
        current: page,
        pageSize
      }
      const res = await postCompanyInfoDetailBranchUnit(params)
      setData(res.list ?? [])
      return res.total ?? 0
    },
    [companyCode]
  )

  const { pagination, resetPageAndTriggerRequest } = usePageChange(initPage, getList)

  useEffect(() => {
    resetPageAndTriggerRequest()
  }, [resetPageAndTriggerRequest])

  const columns = [
    {
      title: '序号',
      key: '序号',
      width: 80,
      render: (_, __, index) => <span>{index + 1 + (pagination.current - 1) * pagination.pageSize}</span>
    },
    {
      title: '分支机构',
      key: 'brOrgName',
      dataIndex: 'brOrgName',
      render: (value, row) => {
        if (value) {
          return (
            <span
              style={{ color: '#1072E0', cursor: 'pointer' }}
              onClick={() => window.open(`/companyDetail?companyCode=${row.brOrgCode}`, '_blank')}>
              {value}
            </span>
          )
        } else {
          return <span>--</span>
        }
      }
    },
    {
      title: '法定代表人',
      key: 'brOrgLegalRep',
      dataIndex: 'brOrgLegalRep',
      render: (value) => <span>{value || '--'}</span>
    },
    {
      title: '成立日期',
      key: 'brOrgFoundDate',
      dataIndex: 'brOrgFoundDate',
      render: (value) => <span>{value || '--'}</span>
    },
    {
      title: '经营状态',
      key: 'brOrgBusinessState',
      dataIndex: 'brOrgBusinessState',
      render: (value) => {
        if (value === '在营(开业)') {
          return <span style={{ color: '#03b915' }}>{value}</span>
        } else if (value === '注销') {
          return <span style={{ color: '#d9001b' }}>{value}</span>
        } else {
          return <span>--</span>
        }
      }
    }
  ]

  return (
    <>
      {data.length > 0 ? (
        <div id="分支机构" className="setBranch">
          <div className="setBranchTitle">分支机构</div>
          <Table columns={columns} dataSource={data} pagination={pagination} rowKey={(row) => row.id} />
        </div>
      ) : null}
    </>
  )
}

export default Branches
